<template>
    <el-menu-item index="5">
        <span @click="handleSetNotice">发布公告</span>
    </el-menu-item>
    <notice-dialog v-model="dialogVisible" :resultData="resultData" />
</template>

<script setup>
import { ref } from "vue";
import * as turf from "@turf/turf";
import { getCurrentInstance, onMounted } from "vue";
import { Query } from "@/api/mapgis-api/Query";
import { FeatureToJson } from "@/api/ol-api/index";
import { setAreaStyle } from "@/api/ol-api/setStyle";
import NoticeDialog from "./NoticeDialog.vue";

//获取地图实例
const { proxy } = getCurrentInstance();

//图层服务：用于查询居民区
const layerService = {
    docName: import.meta.env.VITE_MAPGIS_DOC_NAME,
    layerId: 0,
};

//创建画笔
const drawSource = new ol.source.Vector();
const drawLayer = new ol.layer.Vector({
    source: drawSource,
    style: setAreaStyle({}),
});
const draw = new ol.interaction.Draw({
    source: drawSource,
    type: "LineString",
});
//画笔结束事件
draw.on("drawend", async (e) => {
    //移除画笔
    proxy.$map.removeInteraction(draw);
    //获取画笔的几何信息
    const geometry = e.feature.getGeometry();
    const coordinates = geometry.getCoordinates();

    const line = turf.lineString(coordinates);
    // 创建线的缓冲区，第二个参数是缓冲区的半径（单位是公里）
    const bufferedLine = turf.buffer(line, 0.15);
    //添加到地图
    const feature = new ol.Feature({
        geometry: new ol.geom.Polygon(bufferedLine.geometry.coordinates),
    });
    drawSource.addFeature(feature);
    //查询居民区
    const features = await Query.queryByLayerId(layerService);
    const buildingsGeos = FeatureToJson(features);
    //叠加分析
    const intersects = buildingsGeos.features.filter((building) => {
        const intersect = turf.booleanOverlap(building, bufferedLine);
        return intersect;
    });
    //更新公告显示数据
    resultData.value = intersects.map((intersect) => {
        return {
            name: intersect.properties.values_.name,
            phone: intersect.properties.values_.tel,
        };
    });
    //弹窗显示
    dialogVisible.value = true;
    //清空画笔
    drawSource.clear();
});
//发布公告事件
const handleSetNotice = () => {
    //激活画笔
    proxy.$map.addInteraction(draw);
};

//添加画笔图层
onMounted(() => {
    proxy.$map.addLayer(drawLayer);
});

//弹窗状态
const dialogVisible = ref(false);
//弹窗数据
const resultData = ref([]);
</script>

<style scoped>
span {
    user-select: none;
}
</style>
